import { ref, getCurrentInstance } from 'vue';

export function useDebounce(cb: Function, delay: number) {
  const timer = ref<any>(null);
  const instance = getCurrentInstance();
  let handler = function () {
    clearTimeout(timer.value);
    timer.value = setTimeout(() => {
      cb.apply(instance, arguments);
    }, delay);
  };

  const cancel = () => {
    clearTimeout(timer);
    timer.value = null;
  };

  return {
    handler,
    cancel,
  };
}
